package com.example.server.util;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class RestApiUtil {
    public String loadget(String url,String params) throws Exception
    {
        if (params != null){
            params = params.replace("{","");
            params = params.replace("}","");
            url = url + '?' + params;
        }
        System.out.println(url);
        URL restURL = new URL(url);
        /*
         * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("GET");

        //设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("content-type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("tenantId", "626804036418404352");

        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);

        //读取响应
        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line,resultStr="";

        while(null != (line=bReader.readLine()))
        {
            resultStr +=line;
        }
        bReader.close();
        conn.disconnect();

        return resultStr;

    }

    public String loadpost(String url,Map map) throws Exception
    {
        URL restURL = new URL(url);
        /*
         * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");

        //设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("content-type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);

        // POST请求,包装成json数据
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        String stringparam = JSONUtils.toJSONString(map);

        out.writeBytes(stringparam);
        out.flush();
        out.close();

        //读取响应
        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line,resultStr="";

        while(null != (line=bReader.readLine()))
        {
            resultStr +=line;
        }
        bReader.close();
        conn.disconnect();

        return resultStr;

    }

    public String load(String url,String method,Map map) throws Exception {
        String loadresult = null;
        method = method.toUpperCase();
        System.out.println(method.toUpperCase());
        if (method.equals("GET")){
            if (map !=null){
                loadresult =  loadget(url,map.toString());
            }else {
                loadresult =  loadget(url,null);
            }
        }else if (method.equals("POST")){
            loadresult =  loadpost(url,map);
        }
        return loadresult;
    }

    public static void main(String []args) {try {

        RestApiUtil restUtil = new RestApiUtil();
        Map<String,Object> map = new HashMap<>();
        map.put("id",7);

        Map<String,Object> map1 = new HashMap<>();
        map1.put("name","1");

        String resultString = restUtil.load("http://localhost:8082/api/allEmpfor","get", map1);
        //String resultString = restUtil.loadpost("http://localhost:8082/api/addEmp", "POST", map);

        System.out.println("TX---"+resultString);

    } catch (Exception e) {

        System.out.print(e.getMessage());

    }

    }
}
